#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/11/15 13:40
# file: user.py
# author: lotus163
from typing import Optional, List

from .role import RoleService
from .role_menu import RoleMenuService
from .user_post import UserPostService
from .user_role import UserRoleService
from ...core.custom_exc import CommonException
from ...crud import UserDao, DeptDao, RoleDao, MenuDao
from ...models import SysUserDb
from ...schemas import SysUserSch


class UserService:

    async def check_user_unique(self, userName: str = None, phonenumber: str = None, email: str = None):
        """检查唯一性"""
        # 如果参数有username
        if userName:
            await self._check_unique(err_desc="用户名已存在", userName=userName)
        if phonenumber:
            await self._check_unique(err_desc="手机号已存在", phonenumber=phonenumber)
        if email:
            await self._check_unique(err_desc="邮箱已存在", email=email)

    async def _check_unique(self, err_desc="操作失败,账号/手机号/邮箱已存在.", **kwargs):
        """校验参数是否唯一"""
        user_db = await UserDao.get_db_or_none(**kwargs)
        if user_db:
            raise CommonException(err_desc)

    async def get_all_user_ids(self) -> List[int]:
        user_dbs = await UserDao.get_list_sch()
        return [user_db.userId for user_db in user_dbs]

    async def get_user_all_sch_by_db(self, user_db: SysUserDb) -> SysUserSch:
        # 转成sch
        user_sch = SysUserSch.from_orm(user_db)
        if user_sch.userId == 1:
            user_sch.admin = True
        # 获取roleIds
        user_sch.dept = await DeptDao.get_sch_or_none(deptId=user_sch.deptId)
        user_sch.roleIds = await UserRoleService().get_role_ids_by_user_id(user_sch.userId)
        user_sch.roles = await RoleService().get_role_all_sch_by_ids(user_sch.roleIds,user_sch.deptId)
        user_sch.postIds = await UserPostService().get_post_ids_by_user_id(user_sch.userId)
        return user_sch

    async def get_user_ids_by_dept_ids(self, deptIds: List[int]) -> List[int]:
        users_sch = await UserDao.get_list_sch(deptId__in=deptIds)
        return [user_sch.userId for user_sch in users_sch]
